package com.neusoft.gateway.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    // 令牌私有秘钥
    private static final String SECRET = "yourSecretKey";
    // 定义令牌过期时间的单位
    private static final int calendarField = Calendar.SECOND;
    // 定义令牌的过期时间（单位：秒）
    private static final int calendarInterval = 3600; // 默认1小时

    // 创建令牌的方法
    public static String createToken(Map<String, String> claims) {
        // 确认令牌签发日期、过期时间
        Date issuedAt = new Date();
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expiresAt = nowTime.getTime();

        // 创建令牌
        String token = JWT.create()
                .withHeader(new HashMap<>()) // 添加空头部，避免报错
                .withClaim("userId", claims.get("userId"))
                .withClaim("role", claims.get("role"))
                .withClaim("permissions", claims.get("permissions"))
                .withClaim("mobileJson", claims.get("mobileJson"))
                .withIssuedAt(issuedAt)
                .withExpiresAt(expiresAt)
                .sign(Algorithm.HMAC256(SECRET));

        return token;
    }

    // 验证令牌的方法
    public static Map<String, Claim> verifyToken(String token) throws JWTVerificationException {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT jwt = verifier.verify(token);
        return jwt.getClaims();
    }

    // 解析令牌中的Claims
    public static String parseToken(String token) {
        try {
            Map<String, Claim> claims = verifyToken(token);
            Claim mobileClaim = claims.get("mobileJson");
            return mobileClaim.asString();
        } catch (JWTVerificationException e) {
            // Handle invalid token
            throw new IllegalArgumentException("Invalid token", e);
        }
    }

    // 主方法，用于测试
    public static void main(String[] args) {
        // 创建令牌
        Map<String, String> claims = new HashMap<>();
        claims.put("userId", "123");
        claims.put("role", "admin");
        claims.put("permissions", "read,write,delete");
        claims.put("mobileJson", "{\"mobile\":\"12345678901\"}"); // 添加mobileJson字段
        String token = createToken(claims); // 令牌有效期为默认值
        System.out.println("Generated Token: " + token);

        // 解析令牌
        String parsedClaims = parseToken(token);
        System.out.println("Parsed Claims: " + parsedClaims);
    }
}